package com.qiuzhao.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.support.RetryTemplate;

@Configuration
public class CommonConfiguration {
    @Autowired
    private MySqlChatMemoryRepository mySqlChatMemoryRepository;

    @Bean
    public ChatMemory chatMemory() {
        return MessageWindowChatMemory.builder()
                .chatMemoryRepository(mySqlChatMemoryRepository)
                .maxMessages(200)
                .build();
    }

    @Bean
    public ChatClient chatClient(OpenAiChatModel model) {
        // 定义 Retry 模板：最多重试 3 次，每次延迟 1 秒
        RetryTemplate retryTemplate = RetryTemplate.builder()
                .maxAttempts(3)                // 最大重试次数
                .fixedBackoff(1000)            // 每次间隔 1 秒
                .build();

        return ChatClient.builder(model)
                .defaultAdvisors(
                        new SimpleLoggerAdvisor(),
                        MessageChatMemoryAdvisor.builder(chatMemory()).build()
                )
                .build();
    }
}
